from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views.decorators.http import require_http_methods, require_POST, require_GET

from blog.forms import PubBlogForm
from blog.models import Blog, BlogCategory, BlogComment


# Create your views here.

def index(request):
    #查询blog内容 根据pub_time进行排序
    blogs = Blog.objects.order_by('-pub_time')[:6]
    print(blogs)
    #跳转到首页
    return render(request,'index.html',{'blogs':blogs})

def detail(request,blog_id):
    try:
        #查询详情信息
        blog=Blog.objects.get(pk=blog_id)
    except Exception as e:
        print(e)
        blog=None
    return render(request,'blog_detail.html',{'blog':blog})

# 两种三种写法
# @login_required(login_url=reverse_lazy("zlauth:login"))
# @login_required(login_url='/auth/login')
# 最下面一种需要在配置文件中配置login_url
#必须需要登录，才能发布博客内容
@login_required()
# @require_http_methods([('GET','POST')]) 倒错了
@require_http_methods(['GET','POST'])
def pub_blog(request):
    print("---pub_blog----")
    if request.method == 'GET':
        categories= BlogCategory.objects.all()
        print(categories)
        #跳转到博客发布页面
        return render(request,'pub_blog.html',{'categories':categories})
    else:
        pass
        #发布博客内容
        form=PubBlogForm(request.POST)
        if form.is_valid():
            title=form.cleaned_data.get('title')
            content=form.cleaned_data.get('content')
            category_id=form.cleaned_data.get('category')
            blog=Blog.objects.create(title=title,content=content,category_id=category_id,author=request.user)
            return JsonResponse({'code':'200','msg':'success','data':blog.id})
        else:
            print(form.errors)
            return JsonResponse({'code': '400', "msg": "failed"})

@login_required()
@require_POST
def pub_comment(request):
    blog_id=request.POST.get('blog_id')
    content=request.POST.get('content')
    save=BlogComment.objects.create(blog_id=blog_id,content=content,author=request.user)
    if save:
        print(f"保存评论成功")
    #重新加载博客详情页面
    return redirect(reverse('blog:detail',kwargs={'blog_id':blog_id}))

@require_GET
def search(request):
    keyword=request.GET.get('keyword')
    #从博客的标题和内容中查找关键字的博客 Q对象 多个过滤器逐个调用表示逻辑与关系，同sql语句中where部分的and关键字
    blogs=Blog.objects.filter(Q(title__icontains=keyword)|Q(content__icontains=keyword)).all()
    return render(request,'index.html',{'blogs':blogs})



